#include <io.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>
#define _WIN32_WINT 0x400
using namespace std;
#ifdef _DEBUG
#include <Windows.h>
// maximum mumber of lines the output console should have
static const WORD MAX_CONSOLE_LINES = 500;

void RedirectIOToConsole()
{
	int hConHandle;
	long lStdHandle;
	CONSOLE_SCREEN_BUFFER_INFO coninfo;
	FILE *fp;

	// allocate a console for this app
	AllocConsole();

	// set the screen buffer to be big enough to let us scroll text
	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),&coninfo);
	coninfo.dwSize.Y = MAX_CONSOLE_LINES;
	SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),coninfo.dwSize);

	// redirect unbuffered STDOUT to the console
	lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen( hConHandle, "w" );

	*stdout = *fp;

	setvbuf( stdout, NULL, _IONBF, 0 );

	// redirect unbuffered STDIN to the console

	lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen( hConHandle, "r" );
	*stdin = *fp;
	setvbuf( stdin, NULL, _IONBF, 0 );

	// redirect unbuffered STDERR to the console
	lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen( hConHandle, "w" );

	*stderr = *fp;

	setvbuf( stderr, NULL, _IONBF, 0 );

	// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
	// point to console as well
	ios::sync_with_stdio();
}
#endif

#include <Window\Window.h>
#include <Renderer\Renderer.h>
#pragma comment(lib, "Engine.lib")

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevIsntance, LPSTR lpCmdLine, int nCmdShow)
{
	RedirectIOToConsole();
	MSG msg;
	bool done = false;

	KE::Window* mWindow = KE::Window::GetInstance();
	KE::Renderer* mRender = KE::Renderer::GetInstance();

	if(!mWindow->CreateKWindow(L"Kamin's OpenGL Framework", 640, 480, mWindow->IsFullScreen()))
		return 0;

	while(!done)
	{
		if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			if(msg.message==WM_QUIT)
				done = true;
			else
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
		else
		{
			if(mWindow->IsActive())
			{
				if(mWindow->GetKey(VK_ESCAPE))
					done = true;
				else
				{
					mRender->DrawGLScene();
					mRender->SwapGLBuffers();
				}
				if(mWindow->GetKey(VK_F1))
				{
					mWindow->SetKey(VK_F1, false);
					mWindow->KillWindow();
					mWindow->ToggleFullScreen();
					//Recreate the window
					if(!mWindow->CreateKWindow(L"Kamin's OpenGL Framework", 640, 480, mWindow->IsFullScreen()))
						return 0;
				}
				if(mWindow->GetKey(KeyCode::A))
				{
					mRender->ChangeClearColor(1,1,0,1);
				}
				else if(mWindow->GetKey(KeyCode::S))
				{
					mRender->ChangeClearColor(1,0,0,1);
				}
				else if(mWindow->GetKey(KeyCode::D))
				{
					mRender->ChangeClearColor(0,0,1,1);
				}
			}
		}
	}
	mWindow->KillWindow();
	return(msg.wParam);
}